<?php

namespace App\HttpController\Api\Admin\Device;

use App\HttpController\Api\Admin\AdminBase;
use App\Lib\Utils;
use EasySwoole\Component\Di;
use EasySwoole\Http\Message\Status;
use EasySwoole\FastCache\Cache;
use App\Model\Device\Carousel as CarouselModel;
use App\Model\Device\Group  as GroupModel;

class Carousel extends AdminBase
{

    /**
     * 轮播图列表
     */
    public function index()
    {
        $where = [];
        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $where['name'] = $this->params['name'];
        }

        if (isset($this->params['group_id']) && !empty($this->params['group_id'])) {
            $where['group_id'] = ["%,{$this->params['group_id']},%", 'LIKE'];
        }

        if (isset($this->params['expires']) && !empty($this->params['expires'])) {
            $date = $this->params['date'];
            $dateArr = explode(' - ', $date);
            $firsttime = strtotime($dateArr[0]);
            $lasttime = strtotime($dateArr[1]);
            $where['expires'] = [[$firsttime, $lasttime], 'between'];
        }

        $where['school_code'] = $this->userinfo['school_code'];

        try {
            $columns = '*';
            $carouselObj = new CarouselModel();
            $field = 'id, name, group_id, imgpath, expires, sort';
            $data = $carouselObj->getPageList($field, $where, $this->params['page'], $this->params['limit']);
            $groupObj = new GroupModel;
            $group = $groupObj->getIDName(['school_code' => $this->userinfo['school_code']]);

        } catch(\Exception $e) {

            return $this->toJson(Status::CODE_BAD_REQUEST, "Server Error");
        }

        if (!empty($data['lists'])) {
            $baseINI = \Yaconf::get("basebt");
            $baseINI['urlPrefix'] = 'http://dev.smart_campus_server.com/webroot';

            foreach($data['lists'] as &$list) {
                $list['expires'] = date("Y-m-d", $list['expires']);
                $groupStr = trim($list['group_id'], ',');
                $groupArr = explode(',', $groupStr);

                $list['imgpath'] = $baseINI['urlPrefix'].$list['imgpath'];

                $groupName = '';
                $arr = [];

                foreach ($groupArr as $key => $value) {
                    $groupName .= ','.($group[$value] ?? '');
                    $arr[] = (int)$value;
                }

                $list['groupArr'] = $arr;
                $list['groupName'] = trim($groupName,',');
            }
        }

        $this->response()->withHeader('Content-Type', 'application/json;charset=utf-8');
        $this->response()->write(json_encode([
            'code' => 0,
            'data' => $data['lists'],
            'count' => $data['count'],
        ]));
    }

    /**
     * 添加轮播图
     */
    public function add()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        $data = [];
        if (isset($this->params['name']) && !empty($this->params['name'])){
            $data['name'] = $this->params['name'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入轮播图名称');
        }
        
        if (isset($this->params['sort']) && !empty($this->params['sort'])) {
            $data['sort'] = $this->params['sort'];
        } else {
            $data['sort'] = 1;
        }

        if (isset($this->params['group_id']) && !empty($this->params['group_id'])) {
            $data['group_id'] = ','.implode($this->params['group_id'], ',').',';
        }

        if (isset($this->params['imgpath']) && !empty($this->params['imgpath'])){
            $data['imgpath'] = $this->params['imgpath'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '未上传图片');
        }

        if (isset($this->params['expires']) && !empty($this->params['expires'])){
            $data['expires'] = strtotime($this->params['expires']);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请选择轮播图有效时间');
        }
        
        try {
            $carouselObj = new CarouselModel();
            
            $where = [];
            $where['name'] = $data['name'];
            $where['school_code'] = $this->userinfo['school_code'];

            $isset = $carouselObj->getOne('id', $where);

            if (is_array($isset) && !empty($isset)) {
                return $this->toJson(Status::CODE_CREATED, [], '设备名称已存在');
            }

            $data['userid'] = $this->userinfo['user_id'];
            $data['school_code'] = $this->userinfo['school_code'];
            $data['status'] = 1;

            $result = $carouselObj->add($data);
            if ($result) {
                return $this->toJson(0, ['id' => $result], '添加成功');
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0], '添加失败');
            }
        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }
    }

    /**
     * 编辑轮播图
     */
    public function edit()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        $data = [];
        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $data['name'] = $this->params['name'];
        }
        if (isset($this->params['sort']) && !empty($this->params['sort'])) {
            $data['sort'] = $this->params['sort'];
        }

        if (isset($this->params['group_id']) && !empty($this->params['group_id'])) {
            $data['group_id'] = ','.implode($this->params['group_id'], ',').',';
        }

        if (isset($this->params['imgpath']) && !empty($this->params['imgpath'])) {
            $data['imgpath'] = $this->params['imgpath'];
        }

        if (isset($this->params['expires']) && !empty($this->params['expires'])) {
            $data['expires'] = strtotime($this->params['expires']);
        }

        if (isset($this->params['id']) && !empty($this->params['id'])){
            $id = $this->params['id'];        
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0], '操作数据失败');
        }

        try {
            $carouselObj = new CarouselModel();

            if (isset($data['name'])) {

                $where = [];
                $where['name'] = $data['name'];
                $where['id'] = [$id, '<>'];

                $where['school_code'] = $this->userinfo['school_code'];
                $isset = $carouselObj->getOne('id', $where);

                if (is_array($isset) && !empty($isset)) {
                    return $this->toJson(Status::CODE_CREATED, [], '轮播图名称已存在');
                }
            }
            
            $result = $carouselObj->update($data, ['id' => $id]);
            if ($result) {
                return $this->toJson(0, ['id' => $result], '修改成功');
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, '修改失败', ['id' => 0 ]);
            }
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }
    }

    /**
     * 删除轮播图
     */
    public function delete()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '删除失败');
        }
        
        try {
            $carouselObj = new CarouselModel();
            $result = $carouselObj->destroy($id);
            if ($result) {
                return $this->toJson(Status::CODE_OK, [], '删除成功');
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '删除失败');
            }
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }
    }

    /**
     * 批量删除角色
     * @return [type] [description]
     */
    public function delAll(){
        $ids = $this->params['ids'];

        try {
            $RoleObj = new RoleModel();
            $result = $RoleObj->delAll($ids);
        }catch(\Exception $e) {
            // echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, "Server Error");
        }

        if($result) {
            return $this->toJson(Status::CODE_OK, 'OK', []);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, 'FAIL', []);
        }
    } 

    /**
     * 查询select框中的权限
     * @return [type] [description]
     */
    public function select(){
        try{
            $typeObj = new DeviceTypeModel();

            $data = $typeObj->getIDNameArr([]);
        }catch(\Exception $e){
            return $this->toJson(Status::CODE_BAD_REQUEST,'Server Error');
        }

        if($data){
            return $this->toJson(Status::CODE_OK, 'OK', $data);
        }else{
            return $this->toJson(Status::CODE_BAD_REQUEST, 'FAIL', []);
        }
    }
}
